﻿using Core.Domain;
using Core.IRepository;
using Core.Messages;
using Core.Queries;
using Library.Helpers;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Library.Extensions.Expressions;

namespace Repositories
{
    public class UserRepository : IUserRepository
    {
        UserManager<AppUser, string> userManager;
        private IQueryHelper<AppUser> queryHelper;
        public UserRepository(AppIdentityDbContext context, UserManager<AppUser, string> userManager, IQueryHelper<AppUser> queryHelper)
        {
            this.userManager = userManager;
            this.queryHelper = queryHelper;
            this.queryHelper.Context = context;
        }

        public void Add(AppUser entity)
        {                        
            userManager.Create(entity, entity.Password);
        }

        public void Delete(AppUser entity)
        {
            userManager.Delete(entity);
        }

        public void Delete(Expression<Func<AppUser, bool>> findPredicate)
        {
            throw new NotImplementedException();
        }

        public void Edit(AppUser entity)
        {
            userManager.Update(entity);
        }

        public AppUser FindBy(string id)
        {
            return userManager.FindById(id);
        }

        public IList<string> GerRoles(string id)
        {
            return userManager.GetRoles(id);
        }

        public void AddToRole(string id, string role)
        {
            userManager.AddToRole(id, role);            
        }

        public void RemoveFromRole(string id, string role)
        {
            userManager.RemoveFromRole(id, role);            
        }

        public QueryResponse<AppUser> FindBy(Query<AppUser> query)
        {
            return queryHelper.FindBy(userManager.Users, query);  
        }

        public IList<AppUser> FindBy(Expression<Func<AppUser, bool>> findPredicate)
        {
            return userManager.Users.Where(findPredicate).ToList();
        }

        public IList<AppUser> FindAll()
        {
            return userManager.Users.ToList();
        }
    }
}
